﻿using Microsoft.Extensions.Options;
using MongoDB.Driver;
using SubStationManagement.Server.Models;

namespace SubStationManagement.Server.Services
{
    public class TargetService
    {
        private readonly IMongoCollection<Target> _TargetsCollection;

        public TargetService(
            IOptions<SubStationDatabaseSettings> subStationDatabaseSettings)
        {
            var mongoClient = new MongoClient(
                subStationDatabaseSettings.Value.ConnectionString);

            var mongoDatabase = mongoClient.GetDatabase(
                subStationDatabaseSettings.Value.DatabaseName);

            _TargetsCollection = mongoDatabase.GetCollection<Target>(
                subStationDatabaseSettings.Value.TargetsCollectionName);
        }

        public async Task<List<Target>> GetAsync() =>
            await _TargetsCollection.Find(_ => true).ToListAsync();

        public List<Target> GetAll() =>
            _TargetsCollection.Find(_ => true).ToList();

        public async Task<Target?> GetAsync(string id) =>
            await _TargetsCollection.Find(x => x.Id == id).FirstOrDefaultAsync();

        public async Task CreateAsync(Target newTarget) =>
            await _TargetsCollection.InsertOneAsync(newTarget);

        public async Task UpdateAsync(string id, Target updatedTarget) =>
            await _TargetsCollection.ReplaceOneAsync(x => x.Id == id, updatedTarget);

        public async Task RemoveAsync(string id) =>
            await _TargetsCollection.DeleteOneAsync(x => x.Id == id);
    }
}
